package com.fintech.third.service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.http.client.ClientProtocolException;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.fintech.common.util.PropertiesUtils;
import com.fintech.third.model.ThirdProperties;
import com.fintech.third.model.message.EnterpriseResponse;
import com.fintech.third.model.message.MicroNetResponse;
import com.fintech.third.model.message.ResponseData;
import com.fintech.third.utils.HttpUtil;
import com.fintech.third.utils.MD5Util;
import com.fintech.third.utils.ThirdPropertiesInitUtil;
import com.fintech.third.utils.ThirdSystemUtil;
import com.fintech.third.utils.tencent.SMStUtil;
import com.marvels.common.utils.MarvelsLogUtil;

import net.sf.json.JSONObject;

/**
 * 各短信通道发送处理
 * 
 * @author tangpw
 *
 */
public class SmsChannelSend {
	/**
	 * 腾讯云通道发送短信
	 * 
	 * @param phone
	 * @param templateContent
	 * @return
	 * @throws IOException
	 */
	public static ResponseData tencentSms(String phone, String templateContent) throws IOException {
		ThirdProperties thirdProperties = ThirdPropertiesInitUtil.getThirdProperties();
		/**
		 * 腾讯云短信接口参数
		 */
		String SEND_URL = thirdProperties.getTencent_send_url();
		String TENTCENT_SMS_APPKEY = thirdProperties.getTencent_sms_appkey();
		String SDK_APPID = thirdProperties.getTencent_sdk_appid();

		JSONObject data = new JSONObject();
		JSONObject tel = new JSONObject();
		tel.put("nationcode", "86");
		tel.put("phone", phone);
		data.put("type", "0");
		data.put("msg", templateContent);
		String sig = MD5Util.getMD5(TENTCENT_SMS_APPKEY + phone);
		data.put("sig", sig);
		data.put("tel", tel);

		ResponseData responseData = null;

		responseData = SMStUtil.sendMsg(ThirdSystemUtil.fillStringByArgs(SEND_URL, SDK_APPID, ThirdSystemUtil.getRandom(6)),
				data);

		return responseData;
	}

	/**
	 * 中正云通讯短信
	 * 
	 * @throws URISyntaxException
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static String middleClubSms(String phone, String templateContent) throws Exception {
		/**
		 * 中正云通讯短信接口参数
		 */
		ThirdProperties thirdProperties = ThirdPropertiesInitUtil.getThirdProperties();

		String MERCHANT_ID = thirdProperties.getMiddle_sdk_appid();// 中正云通信帐号
		String MERCHANT_PWD = thirdProperties.getMiddle_sms_appkey();// 中正云通信密码
		String MIDDLE_SEND_URL = thirdProperties.getMiddle_send_url();

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", URLEncoder.encode(MERCHANT_ID, "gb2312"));
		map.put("pwd", MERCHANT_PWD);
		map.put("to", phone);
		map.put("content", URLEncoder.encode(templateContent, "gb2312"));
		String urlStringBuffer = ThirdSystemUtil.paramsAssembling(map, MIDDLE_SEND_URL);
		String returnResult = "";

		try{
			returnResult = HttpUtil.httpPost(urlStringBuffer, "");
		}catch(Exception e){
			MarvelsLogUtil.getInstance().error(">>>>>>>>>>中正云通讯短信发送异常:"+e+",手机号:"+phone);
		}
		

		MarvelsLogUtil.getInstance().info("=============>>>>中正云通讯短信返回参数:" + returnResult);
		return returnResult;
	}

	/**
	 * 微网通联短信
	 * 
	 * @param phone
	 * @param templateContent
	 * @return
	 */
	public static MicroNetResponse microNetcomSms(String phone, String templateContent,String messageCategory) {
		ThirdProperties thirdProperties = ThirdPropertiesInitUtil.getThirdProperties();
		String MICRONET_URL = thirdProperties.getWt_sms_url();
		String MICRONET_SNAME = thirdProperties.getWt_sms_sname();
		String MICRONET_SPWD = thirdProperties.getWt_sms_spwd();
		Map<String, Object> map = new HashMap<String, Object>();
		MicroNetResponse microNetResponse = new MicroNetResponse();
		String suffix = PropertiesUtils.getString("sms.suffix");
		String returnResult = "";
		map.put("sname", MICRONET_SNAME);
		map.put("spwd", MICRONET_SPWD);
		map.put("scorpid", "");
		if(messageCategory.equals("1")){//行业触发
			map.put("sprdid", "1012888");
			MarvelsLogUtil.getInstance().info("===============微网通联短信类别为行业触发");
		}else if(messageCategory.equals("2")){//营销
			map.put("sprdid", "1012812");
			MarvelsLogUtil.getInstance().info("===============微网通联短信类别为营销");
		}else if(messageCategory.equals("3")){//行业通知
			map.put("sprdid", "1012808");
			MarvelsLogUtil.getInstance().info("===============微网通联短信类别为行业通知");//行业通知
		}
		map.put("sdst", phone);
		try {
			map.put("smsg", URLEncoder.encode(templateContent + "【" + suffix + "】", "UTF-8"));
		} catch (Exception e1) {
			e1.printStackTrace();
			MarvelsLogUtil.getInstance().info("===========>>>微网通联短信请求参数拼装异常");
		}
		String requestParams = ThirdSystemUtil.paramsAssembling(map, "");
		MarvelsLogUtil.getInstance().info("=============>>>>微网通联短信请求参数:" + requestParams);
		try {
			// returnResult = HttpUtil.httpPost(MICRONET_URL, requestParams);
			returnResult = SMStUtil.SMS(requestParams, MICRONET_URL);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>>>手机号:"+phone+",微网通联短信发送异常:",e);
		}
		if (StringUtils.isNotEmpty(returnResult)) {
			microNetResponse = ThirdSystemUtil.xmlToEntity(returnResult, MicroNetResponse.class);
		}
		MarvelsLogUtil.getInstance().info("=============>>>>微网通联短信返回参数:" + returnResult);
		return microNetResponse;

	}

	/**
	 * 速盾科技短信
	 * 
	 * @param phone
	 * @param templateContent
	 * @return
	 */
	public static String SpeedShieldTechnology(Map<String, String> hashMap) {
		ThirdProperties thirdProperties = ThirdPropertiesInitUtil.getThirdProperties();
		String mobile = hashMap.get("mobile");
		Map<String, String> map = new HashMap<String, String>();
		map.put("account", thirdProperties.getSpeed_shield_account());
		map.put("pswd", thirdProperties.getSpeed_shield_pswd());
		map.put("mobile", mobile);
		try {
			map.put("msg", hashMap.get("msg"));
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		map.put("needstatus", "true");
		map.put("extno", new SimpleDateFormat("yyyyMMdd").format(new Date()));
		String result = "";
		try {
			result = HttpUtil.postSpeedShield2(thirdProperties.getSpeed_shield_url(), map);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("=============速盾科技短信请求手机号:" + mobile + ",异常:" + e);
			return result;
		}
		MarvelsLogUtil.getInstance().info("=============速盾科技短信响应结果:" + result + ",手机号码:" + mobile);
		return result;

	}

	/**
	 * 速盾科技短信(催收类别)
	 * 
	 * @param phone
	 * @param templateContent
	 * @return
	 */
	public static String SpeedShieldTechnologyCollection(Map<String, String> hashMap) {
		ThirdProperties thirdProperties = ThirdPropertiesInitUtil.getThirdProperties();
		String mobile = hashMap.get("mobile");
		Map<String, String> map = new HashMap<String, String>();
		map.put("userid", thirdProperties.getSpeed_shield_userId());
		map.put("account", thirdProperties.getSpeed_shield_account_collection());
		map.put("password", thirdProperties.getSpeed_shield_pswd_collection());
		map.put("mobile", mobile);
		try {
			map.put("content", hashMap.get("msg"));
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		map.put("action", "send");
		map.put("extno", new SimpleDateFormat("yyyyMMdd").format(new Date()));
		String result = "";
		try {
			result = HttpUtil.postSpeedShield2(thirdProperties.getSpeed_shield_url_collection(), map);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>>>>>速盾科技短信(催收)请求手机号:" + mobile + ",异常:" + e);
			return result;
		}
		MarvelsLogUtil.getInstance().info(">>>>>>>>>>>>>速盾科技短信(催收)响应结果:" + result + ",手机号码:" + mobile);
		if(StringUtils.isNotEmpty(result)){
			Document doc;
			Map<String, String> docMap=new HashMap<String,String>();
			try {
				doc = DocumentHelper.parseText(result);
				Element root = doc.getRootElement();
				List<Element> elements = root.elements();
				for (Iterator<Element> it = elements.iterator(); it.hasNext();) {
					Element element = it.next();
					docMap.put(element.getName(), element.getText());
				}
			} catch (DocumentException e) {
				MarvelsLogUtil.getInstance().error(">>>>>>>>>>>>速盾科技短信(催收)请求手机号:" + mobile + ",返回参数解析异常:" + e);
			} 
			int status=docMap.get("returnstatus").equals("Success")?0:1;
			return result=docMap.get("remainpoint")+","+status+"\n"+"collection";
		}
		return result;
	}
	
	
	/**
	 * 创蓝短信
	 * @param hashMap
	 * @return
	 */
	public static String  createBuleMsg(Map<String, String> hashMap){
		ThirdProperties thirdProperties=ThirdPropertiesInitUtil.getThirdProperties();
		String requestUrl=thirdProperties.getCl_request_url();
		JSONObject jsonObject=new JSONObject();
		String mobile = hashMap.get("mobile");
		String msg=hashMap.get("msg");
		String messageCategory=hashMap.get("messageCategory");
		String result="";
		if(messageCategory.equals("2")){//会员营销短信
			jsonObject.put("account",thirdProperties.getCl_marketing_accout());
			jsonObject.put("password", thirdProperties.getCl_marketing_password());
		}else{
			jsonObject.put("account", thirdProperties.getCl_verify_code_accout());
			jsonObject.put("password",thirdProperties.getCl_cl_verify_code_password());
		}
		jsonObject.put("msg",thirdProperties.getCl_sign_name()+msg);
		jsonObject.put("phone", mobile);
		jsonObject.put("sendtime", "");
		jsonObject.put("report", "true");
		jsonObject.put("extend", "");
		MarvelsLogUtil.getInstance().info("===============调用创蓝短信开始,手机号:"+mobile);
		try {
			result=HttpUtil.httpPost(requestUrl, jsonObject.toString());
			MarvelsLogUtil.getInstance().info("===========创蓝短信发送请求手机号:"+mobile+",结果:"+result);
		}catch (Exception e) {
			MarvelsLogUtil.getInstance().error("===========创蓝短信发送请求手机号:"+mobile+",异常:"+e);
		}
		return result;
	}
	
	
	
	
	/**
	 * 梦网短信
	 * @param hashMap
	 * @return
	 */
	public static String monternetMsg(Map<String, String> hashMap) {
		ThirdProperties  thirdProperties=ThirdPropertiesInitUtil.getThirdProperties();
		String requestUrl =thirdProperties.getMw_request_url();
		JSONObject jsonObject = new JSONObject();
		String userId = "";
		String pwd = "";
		String mobile = hashMap.get("mobile");
		String msg = hashMap.get("msg");
		String messageCategory = hashMap.get("messageCategory");
		if(messageCategory.equals("2")){//会员营销短信
			userId=thirdProperties.getMw_market_userId();
			pwd= thirdProperties.getMw_market_pwd();
		}else{
			userId=thirdProperties.getMw_message_userId();
			pwd=thirdProperties.getMw_message_pwd();
		}
		String result = "";
		jsonObject.put("userid", userId);
		MessageDigest messageDigest;
		StringBuffer md5StrBuff = new StringBuffer();
		String timestamp=new SimpleDateFormat("MMddHHmmss").format(Calendar.getInstance().getTime());
		try {
			messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.reset();
			messageDigest.update((userId + "00000000" + pwd
					+ timestamp).getBytes("UTF-8"));
			byte[] byteArray = messageDigest.digest();
			for (int i = 0; i < byteArray.length; i++) {
				if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) {
					md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
				} else {
					md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
				}
			}

		} catch (Exception e2) {
			e2.printStackTrace();
		}
		jsonObject.put("pwd", md5StrBuff.toString());
		jsonObject.put("mobile", mobile);
		jsonObject.put("timestamp", timestamp);
		try {
			jsonObject.put("content", URLEncoder.encode(msg, "GBK"));
		} catch (UnsupportedEncodingException e1) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>>>>>>>梦网短信发送请求手机号:" + mobile + ",URLEncoder.encode异常:" + e1);
		}
		try {
			MarvelsLogUtil.getInstance().info("============梦网请求参数:"+jsonObject.toString());
			result = HttpUtil.httpPost(requestUrl, jsonObject.toString());
			MarvelsLogUtil.getInstance().info("===========梦网短信发送请求手机号:" + mobile + ",结果:" + result);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>>>>>>>梦网短信发送请求手机号:" + mobile + ",异常:" + e);
		}
		return result;
	}
	
	
	
	
	/**
	 * 烽火短信
	 * @param hashMap
	 * @return
	 */
	public static String fengHuoMsg(Map<String, String> hashMap){
		ThirdProperties thirdProperties=ThirdPropertiesInitUtil.getThirdProperties();
		String requestUrl=thirdProperties.getBj_fh_request_url();
		String name="";//账号
		String password="";//密码
		String messageCategory = hashMap.get("messageCategory");
		if(messageCategory.equals("2")){//会员营销短信
			name=thirdProperties.getBj_fh_account_yx();
			password=thirdProperties.getBj_fh_password_yx();
		}else{//行业
			name=thirdProperties.getBj_fh_account_hy();
			password=thirdProperties.getBj_fh_password_hy();
		}
		String seed=new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		String dest=hashMap.get("mobile");//手机号码
		String key=MD5Util.getMD5(MD5Util.getMD5(password)+seed).toLowerCase();
		String content= hashMap.get("msg");//内容
		Map<String, Object> dataMap=new HashMap<>();
		dataMap.put("name", name);
		dataMap.put("seed", seed);
		dataMap.put("key", key);
		dataMap.put("dest", dest);
		try {
			dataMap.put("content",URLEncoder.encode(thirdProperties.getBj_fh_sign_name()+content, "UTF-8"));
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		MarvelsLogUtil.getInstance().info("=========北京烽火短信请求信息:"+JSONObject.fromObject(dataMap));
		String finalRequestUrl=ThirdSystemUtil.paramsAssembling(dataMap,requestUrl);
		String result="";
		try {
			result=HttpUtil.httpPost(finalRequestUrl);
		}catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>>>>>>>>>北京烽火短信请求异常:"+e+",手机号:"+dest);
		}
		return result;
	}
	
	
	/**
	 * 企业短信通接口
	 * @param hashMap
	 * @return
	 */
	public static EnterpriseResponse EnterpriseMsg(Map<String, String> hashMap){
		ThirdProperties  thirdProperties=ThirdPropertiesInitUtil.getThirdProperties();
		String userid="";
		Date date=new Date();
		String account="";
		String password="";
		String timestamp=new SimpleDateFormat("yyyyMMddHHmmss").format(date);
		String mobile=hashMap.get("mobile");
		String content=hashMap.get("msg");
		String sendTime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
		String action="send";
		String messageCategory = hashMap.get("messageCategory");
		if(messageCategory.equals("2")){//会员营销短信
			userid=thirdProperties.getEnterpriseMsg_userid_yx();
			account=thirdProperties.getEnterpriseMsg_account_yx();
			password=thirdProperties.getEnterpriseMsg_password_yx();
		}else{
			userid=thirdProperties.getEnterpriseMsg_userid_hy();
			account=thirdProperties.getEnterpriseMsg_account_hy();
			password=thirdProperties.getEnterpriseMsg_password_hy();
		}
		String extno=ThirdSystemUtil.randomNumber(9);
		String requestUrl=thirdProperties.getEnterpriseMsg_requestUrl();
		Map<String, Object> dataMap=new HashMap<String, Object>();
		dataMap.put("action", action);
		dataMap.put("userid", userid);
		dataMap.put("timestamp", timestamp);
		dataMap.put("sign", MD5Util.getMD5(account+password+timestamp).toLowerCase());
		dataMap.put("mobile", mobile);
		try {
			dataMap.put("sendTime", URLEncoder.encode(sendTime,"UTF-8"));
			dataMap.put("content", URLEncoder.encode(thirdProperties.getEnterpriseMsg_sign_name()+content,"UTF-8"));
		} catch (UnsupportedEncodingException e1) {
			MarvelsLogUtil.getInstance().error("=========企业短信通短信URLEncoder.encode异常:"+e1+",手机号:"+mobile);
		}
		dataMap.put("extno", extno);
		String finalRequestUrl=ThirdSystemUtil.paramsAssembling(dataMap,requestUrl);
		String result="";
		try {
			result=HttpUtil.httpPost(finalRequestUrl);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>>>>>>>企业短信通短信发送请求异常:"+e+",手机号:"+mobile);
		}
		MarvelsLogUtil.getInstance().info("=========企业短信通接口手机号:"+mobile+",账号:"+account+"请求参数"+finalRequestUrl+",返回参数"+result);
		EnterpriseResponse rnterpriseResponse=new EnterpriseResponse();
		if(StringUtils.isNotEmpty(result)){
			rnterpriseResponse=ThirdSystemUtil.xmlToEntity(result,EnterpriseResponse.class);
		}
		return rnterpriseResponse;
	}
	
	public static void main(String[] args){
		Map<String, String> map = new HashMap<String, String>();
		map.put("mobile", "18397748754");
		map.put("msg", "【云科贷】您的验证是123");
		map.put("messageCategory","1");
	//	String result=SmsChannelSend.createBuleMsg(map);
		
		EnterpriseResponse enterpriseResponse=SmsChannelSend.EnterpriseMsg(map);
	}
}
